﻿using System.Collections;
using System.Collections.Generic;
using Components;
using Const;
using Entitas;
using UnityEngine;

public class ClickSystem : ReactiveSystem<InputEntity>
{
    private Contexts _contexts;
    private ClickComponent _lastClick;
    
    public ClickSystem(Contexts context) : base(context.input)
    {
        _contexts = context;
    }

    protected override ICollector<InputEntity> GetTrigger(IContext<InputEntity> context)
    {
        return context.CreateCollector(InputMatcher.ComponentsClick);
    }

    protected override bool Filter(InputEntity entity)
    {
        return entity.hasComponentsClick;
    }

    protected override void Execute(List<InputEntity> entities)
    {
        if (entities.Count == 1)
        {
            InputEntity input = entities.SingleEntity();
            var click = input.componentsClick;
            bool isMovable = _contexts.game
                .GetEntitiesWithComponentsItemIndex(new customData(click.x, click.y))
                .SingleEntity()
                .isComponentsMovable;
//            _contexts.game
//                .GetEntitiesWithComponentsItemIndex(new customData(click.x, click.y))
//                .SingleEntity()
//                .ReplaceComponentsExchange(ExchangeState.START);
            if (isMovable)
            {
                if (_lastClick == null)
                {
                    _lastClick = click;
                }
                else
                {
                    if ((click.x == _lastClick.x - 1) && (click.y == _lastClick.y)
                        || (click.x == _lastClick.x) && (click.y == _lastClick.y + 1)
                        || (click.x == _lastClick.x + 1) && (click.y == _lastClick.y)
                        || (click.x == _lastClick.x) && (click.y == _lastClick.y - 1)
                    )
                    {
                        //Debug.Log("related");
                        //TODO:交换Item
                        ReplaceExchange(click);
                        ReplaceExchange(_lastClick);
                        
                        _lastClick = null;
                    }
                }
            }   
        }  
    }

    private void ReplaceExchange(ClickComponent click)
    {
        var entities = _contexts.game
            .GetEntitiesWithComponentsItemIndex(new customData(click.x, click.y));
        if (entities.Count > 0)
        {
            foreach (GameEntity entity in entities)
            {
                entity.ReplaceComponentsExchange(ExchangeState.START);
            }
        }
    }
    
}
